package lk.icta.core.dao.impl;

import lk.icta.common.AppConstants;
import lk.icta.common.ErrorCodes;
import lk.icta.common.dao.impl.BaseDAO;
import lk.icta.core.dao.BoundaryTypeDAO;
import lk.icta.core.entity.BoundaryType;
import lk.icta.user.entity.User;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Duminda Dharmakeerthi
 */
public class BoundaryTypeDAOImpl extends BaseDAO implements BoundaryTypeDAO {

    private final Map<Integer, String> siNames = new HashMap<Integer, String>();
    private final Map<Integer, String> enNames = new HashMap<Integer, String>();
    private final Map<Integer, String> taNames = new HashMap<Integer, String>();

    @Transactional(propagation = Propagation.SUPPORTS)
    public BoundaryType getBoundaryTypeById(int id, User user) {
        logger.debug("Loading boundary type {} by {}", id, user.getUsername());
        return em.find(BoundaryType.class, id);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public Map<Integer, String> getAllBoundaryTypesByUserLanguage(String language, User user) {
        logger.debug("Listing boundary types in {} by {}", language, user.getUsername());
        Query q = em.createNamedQuery("getAllBoundaryTypesByUserLanguage");
        List<BoundaryType> boundaryTypeList = q.getResultList();
        for (BoundaryType boundaryType : boundaryTypeList) {
            siNames.put(boundaryType.getId(), boundaryType.getSiTypeName());
            enNames.put(boundaryType.getId(), boundaryType.getEnTypeName());
            taNames.put(boundaryType.getId(), boundaryType.getTaTypeName());
        }
        if (AppConstants.SINHALA.equals(language)) {
            return siNames;
        } else if (AppConstants.ENGLISH.equals(language)) {
            return enNames;
        } else if (AppConstants.TAMIL.equals(language)) {
            return taNames;
        } else {
            handleException("Unsupported language : " + language, ErrorCodes.INVALID_LANGUAGE);
        }
        return Collections.emptyMap();
    }
}
